import { useEffect, useState } from 'react'
import styles from './index.module.less'
import classnames from 'classnames';

const CheckListButton = ({
  options,
  value,
  defaultValue,
  onChange,
  isRadio,
  readonly
}: {
  options: [{ label: string, value: any }],
  value?: any,
  defaultValue?: any,
  onChange?: Function,
  isRadio?: boolean | undefined,
  readonly?: boolean | undefined,
}) => {

  console.log('value :>> ', value);

  if (!Array.isArray(options)) return null;

  const [selectList, setSelectList] = useState(value ?? defaultValue ?? []);
  console.log('selectList ------:>> ', value, defaultValue, selectList);

  useEffect(() => {
    if (value) {
      setSelectList(value)
    }
  }, [value])

  // useEffect(() => {
  //   onChange && onChange(selectList)
  // }, [selectList])

  function onSelect(li: any) {
    if (readonly) return;

    if (isRadio) {
      setSelectList([li?.value])
      onChange && onChange([li?.value])
    } else {
      const newList = JSON.parse(JSON.stringify(selectList))
      const index = newList.findIndex((item: any) => item == li.value)
      if (index > -1) {
        newList.splice(index, 1);
        setSelectList(newList)
        onChange && onChange(newList)
      } else {
        setSelectList((prv: any) => [...prv, li.value])
        onChange && onChange([...newList, li.value])
      }
    }
  }


  return (
    <div className={styles.list}>
      {
        options.map((item, index) => {
          const isActive = selectList?.findIndex((li: any) => li == item.value);
          return (
            <div
              className={classnames(styles.botton, { [styles.isActive]: isActive > -1 })}
              onClick={() => onSelect(item)}
              key={index}
            >
              {item.label}
            </div>
          )
        })
      }

    </div>
  )
}

export default CheckListButton